<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html>
	<head>
		<meta charset="UTF-8">
		<title>未来小说网--写小说</title>
		<link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css">
		<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
		<link rel="stylesheet" href="../../resources/font/iconfont.css" th:href="@{/resources/font/iconfont.css}">
		<link rel="stylesheet" href="../../resources/css/writer.css" th:href="@{/resources/css/writer.css}">
		<script th:inline="javascript">
			let contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
		</script>
			<!--这里设置 class="content" 套用TinyMCE编辑器-->
	</head>
	<body style="background-color: rgb(245,245,245);">
		<p id="SectionId" style="display: none"></p>
		<div class="modify-chapter">
			<div class="box4">
				<p id="SID"></p>
			<input type="text" id="modify-chapter-name" class="form-inputs">
			<button class="btn-sure">确定修改</button>
			</div>
		</div>
		<div class="modify-Novel">
			<div class="box3">
				<div class="work-info">
					<div class="top-title">
						<div class="top-title-box">
							<span style="line-height: 50px;font-size:17px;color: white;float: left;">修改作品</span>
							<img id="closeInfo" src="../../resources/img/close.png" style="width: 20px;height: 20px;display: inline-block;float: right;margin-top: 15px" th:src="@{/resources/img/close.png}"/></div>
					</div>
					<div class="work-info-form">
						<div class="form-box">
							<div class="form-list">
								<dl>
									<dd class="">
										<span>标题</span>
										<input name="book-name" id="book-name" class="form-inputs" type="text" required>
										<p>15字内，请勿添加书名号等特殊符号</p>
									</dd>
									<dd>
										<span>系列</span>
										<input id="book-type" class="form-inputs" style="width: 200px;" type="text" required>
										<p>例如：魔幻，武侠，都市....</p>
									</dd>
									<dd>
										<span>版权</span>
										<select id="copyright">
											<option selected>-请选择-</option>
											<option>公版</option>
											<option>转载</option>
											<option>同人</option>
											<option>原创</option>
										</select>
									</dd>
									<dd>
										<span>作品分类标签(输入空格隔开标签)</span>
										<input style="height: 30px;padding: 0;resize: none;" id="book-tags" list="tag" class="form-inputs">
										<datalist id="tag">

										</datalist>
										<div class="tags">

										</div>

									</dd>
									<dd>
										<span>作者(输入空格隔开作者)</span>
										<input style="height: 30px;padding: 0;resize: none;" id="book-act" class="form-inputs">
										<div class="acts">

										</div>

									</dd>
									<dd>
										<span>出版社</span>
										<input name="book-press" id="book-press" class="form-inputs" type="text" required>
									</dd>
								</dl>
							</div>
							<div class="create">
								<button type="button" id="create-work" data-toggle="modal" data-target="#myModal">创建作品</button>
							</div>
						</div>
					</div>
				</div>

				<div class="Insert-picture">
					<p>请插入封面图片</p>
					<form action="" style="text-align: center">
						<input type="file" style="margin: 0 10px;" id="image_file"  name="image_file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
					</form>
					<img src="../../resources/img/addimg.png" th:src="@{/resources/img/addimg.png}" id="addIMG"/>
					<div class="img-box" style="display: block">
						<input id="sure"  type="submit"></input>
					</div>

				</div>
			</div>
		</div>
		<div class="writer-wrep">
			<div class="writer-tabs">
				<div class="MyWorks" style="line-height: 40px;border-bottom: rgba(0,0,0,0.2) 1px solid;padding:0 20px;">
				<span style="color: #7a7a7a;" id="BOOKNAME">书名</span>
				</div>
				<ul class="writer-list"style="overflow: auto;">
					<li th:each="chapter1:${novel}">
						<div class='writer-lis'>
							<button class="modify" th:attr="chapterid=${chapter1.uniqueId}">添加</button>
							<button class="delete" th:attr="chapterid=${chapter1.uniqueId}">删除</button>
							<button class="add" th:attr="chapterid=${chapter1.uniqueId}">修改</button>
							<p style="display: none" class="getId" th:text="${chapter1.uniqueId}"></p>
							<div class="first" style='display: block'>
								<p th:text="${chapter1.title}"></p>
								<i class="fa fa-caret-right rotate"></i>
								<p th:text="共+${chapter1.size()}+节"></p>
							</div>
							<div class='sec' chapterId='"+data.thisUUID+"'>
								<div class='works-content' th:attr="chapterid=${chapter1.uniqueId}" th:each="section1 : ${chapter1}">
									<span class="neirong" th:text="${section1.title}"></span>
									<button class="modify2" th:attr="sectionid=${section1.uniqueId}">修改</button>
									<button class="delete2" th:attr="sectionid=${section1.uniqueId}">删除</button>
								</div>
							</div>
						</div>
					</li>
				</ul>
			</div>
			<div class="writer-body">
				<form action="" method="">
					<p>
						<input type="text" name="bookName"  placeholder="输入章节名称" id="book-name2" class="writer-inputs"/>
						<button type="button" id="sure-bookName">确定</button>
						<button type="button" id="modify-novel">修改书籍信息</button>
					</p>
					<div class="box">
						<p><input type="text" name="titleName" placeholder="请输入小结" id="title-name" class="writer-inputs"/></p>
						<p><textarea name="content" class="content"></textarea></p>
					<!--先暂时写成button类型，等前后端交互再改成submit类型-->
					<p style="text-align: center;"><input type="button" value="发布" id="writer-release"/></p>
					</div>
				</form>
			</div>
		</div>
		<script src="../../resources/js/writer.js" th:src="@{/resources/js/writer.js}"></script>
		<script src="../../resources/tinymce/tinymce.min.js" th:src="@{/resources/tinymce/tinymce.min.js}"></script>
		<script th:inline="javascript" async>
			function popup_over(icon,color,contant){
				$('body').append('<div class="popup_over" style="text-align: center; line-height: 80px; left: 50%; top: 50%; transform: translate(-50%,-50%); background-color: white; position: fixed; width: 180px; height: 80px; border: 1px solid #D5D6D5; z-index: 1000;"><i class="iconfont '+icon+'" style="font-size: 30px;color: '+color+';"></i><span style="font-size: 16px; position: relative; bottom: 5px;"> '+contant+'</span></div>');
				setTimeout(function(){
					$('.popup_over').remove();
					// clear('.popup_over');
				},1500)
			};
			//标签
			$("#book-tags").keydown(function(event) {
				if (event.keyCode == 32) {
					if ($("#book-tags").val().length >= 5) {
						alert("标签不得超过三个字")
						$("#book-tags").val("");
					} else {
						var str = $("#book-tags").val();
						var test = " <div class=\"tags-s\">\n" +
								"<a href=\"###\" class=\"tags-text\">" + str + "</a>\n" +
								"<i class=\"fa fa-close close2\" ></i>\n" +
								"</div>";
						$(".tags").append(test);
						$("#book-tags").val("");
					}
				}
			});
			//作者
			$("#book-act").keydown(function(event) {
				if (event.keyCode == 32) {
					var str = $("#book-act").val();
					var test = " <div class=\"tags-s\">\n" +
							"<a href=\"###\" class=\"tags-text2\">" + str + "</a>\n" +
							"<i class=\"fa fa-close close2\" ></i>\n" +
							"</div>";
					$(".acts").append(test);
					$("#book-act").val("");
				}
			});

			$(".tags").on('click', '.close2', function() {
				$(this).parent().remove();
			});
			$(".acts").on('click', '.close2', function() {
				$(this).parent().remove();
			});
			//得到书籍的所有信息
			function GetAllInfo(){
				$.ajax({
					url:/*[[${#request.getContextPath()} + '/api/novel/' + ${novel.uniqueId.toString()}]]*/"/nonexist",
					type: "GET",
					datatype:"json",
					contentType: "application/json;charset=UTF-8",
					data: {},
					success:function (data) {
						console.log("书本信息")
						console.log(data);
						$("#BOOKNAME").text(data.title);
						//for (var i=0;i<data.chapters.length;i++){
							//打印数据的同时将小说章节的id获取
						//	$(".writer-list ").prepend("<li><div class='writer-lis'><button class='modify'  chapterId='"+data.chapters[i].uniqueId+"'>修改</button><button class='delete'  chapterId='"+data.chapters[i].uniqueId+"'>删除</button><p style='display: none'>" + "" + data.chapters[i].uniqueId+ "" + "</p><div class=\"first\" chapterId='"+data.chapters[i].uniqueId+"' style='display: block'><p>" + "" + data.chapters[i].title+ "" + "</p><i class=\"fa fa-caret-right rotate\"></i><p>共有0节</p></div><div class='sec' chapterId='"+data.chapters[i].uniqueId+"' ></div></div></li>\n");
						//}

					},
					// error: function(jqXHR, textStatus, errorThrown) {
					// 	const data = JSON.parse(jqXHR.responseText);
					// 	alert("发送失败，请稍候再试:" + data.errorMessage);
					// }
					error: function(data) {
					}
				})
			}
		//	GetAllInfo();
			//添加章节
			function AddTitle(){
				$.ajax({
					url:/*[[${#request.getContextPath()} + '/api/novel/' + ${novel.uniqueId.toString()} + '/addChapter']]*/"/nonexist",
					type: "post",
					datatype:"json",
					contentType: "application/json;charset=UTF-8",
					data: JSON.stringify({
						title:$("#book-name2").val().length==0?null:$("#book-name2").val().length,
					}),success:function (data) {
						//保存章节id和小说id
						//localStorage.setItem("parentUUID",data.parentUUID);
						//localStorage.setItem("thisUUID",data.thisUUID);
						//localStorage.setItem("title",data.title);
						console.log("章节信息")
						popup_over('icon-happy-l','#00ff0f',"添加章节成功");
						setTimeout(function () {
							window.location.reload();
						},0)
						console.log(data)
					},error:function (data) {
						console.log(data);
					}
				});
			}
			//添加小节
			function AddSection(thisID) {
				var str =/*[[${#request.getContextPath()} + '/api/novel/' + ${novel.uniqueId.toString()}]]*/;
				//获取富文本编辑器内的内容
				var activeEditor = tinymce.activeEditor;
				var editBody = activeEditor.getBody();
				activeEditor.selection.select(editBody);
				var text = activeEditor.selection.getContent({"format": "html"});
				var Text = activeEditor.selection.getContent({"format": "text"});
				var TextLength = Text.length;
				if (text.length == 1) {
					popup_over('icon-happy-l','#00ff0f',"内容不能为空");
				} else {
					//创建小节的交互
					$.ajax({
						url:str+'/'+thisID+'/addSection',
						type: "post",
						datatype:"json",
						contentType: "application/json;charset=UTF-8",
						data: JSON.stringify({
							title:$("#title-name").val(),
							text:text,
						}),
						success:function (data) {
							$("#SID").text(data.title);
							alert($("#SID").text());
							getTitleId(data.uniqueId);
							popup_over('icon-happy-l','#00ff0f',"添加小节成功");
						$(".box").css("display","none");
						}, error: function(jqXHR, textStatus, errorThrown) {
							const data = JSON.parse(jqXHR.responseText);
							alert("发送失败，请稍候再试:" + data.errorMessage);
						}
					})
				}
			}
			//获取内容
			function getTitleId(titleId) {
				const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
				$.ajax({
					url:contextPath+"/api/novel/section/"+titleId,
					type: "GET",
					datatype:"json",
					contentType: "application/json;charset=UTF-8",
					data: {},
					success:function (data) {
						console.log("内容信息")
						console.log(data);
						localStorage.setItem("Text",data.text)
					},
					error: function(data) {
						console.log(data);
					}
				})
			}
			//删除章节
			$(".writer-list").on('click','.delete',function(){
				var thisSectionId = $(this).attr("chapterid");
				const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
				$.ajax({
					url:contextPath+"/api/novel/chapter/"+thisSectionId,
					type:"delete",
					datatype:"json",
					contentType: "application/json;charset=UTF-8",
					data: {},
					success:function (data) {
						popup_over('icon-happy-l','#00ff0f',"删除章节成功");
					},error:function (data) {
						console.log(data);
					}
				})
				$(this).parent().parent().remove();
			})
			//删除小节
			$(".writer-list").on('click','.delete2',function(){
				var thisTitleId = $(this).attr("sectionId");
				const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
				$.ajax({
					url:contextPath+"/api/novel/section/"+thisTitleId,
					type:"delete",
					datatype:"json",
					contentType: "application/json;charset=UTF-8",
					data: {},
					success:function (data) {
						popup_over('icon-happy-l','#00ff0f',"删除小节成功");
					},error:function (data) {
						console.log(data);
					}
				})
				$(this).parent().remove();
			})
			//获取创建小说的日期
			function getNowFormatDate() {
				var date = new Date();
				var month = date.getMonth() + 1;
				var strDate = date.getDate();
				var minute = date.getMinutes();
				var seconds= date.getSeconds();
				if (month >= 1 && month <= 9) {
					month = "0" + month;
				}
				if (strDate >= 0 && strDate <= 9) {
					strDate = "0" + strDate;
				}
				if (minute >= 0 && minute <= 9) {
					minute = "0" + minute;
				}
				if (seconds >= 0 && seconds <= 9) {
					seconds = "0" + seconds;
				}
				var currentdate = date.getFullYear() + '年' + month + '月' + strDate
						+ '日 ' + date.getHours() + ':' + minute+':'+seconds;
				return currentdate;
			}
			//修改小说信息
			$("#create-work").click(function () {
				var copyright = $("#copyright").val();
				var BookType = $("#book-type").val();
				var BookPrese = $("#book-press").val();
				var BookIntro = $("#book-intro").val();
				var BookName = $("#book-name").val();
				var $inputArr = $('.tags-text');
				var result = [];
				$inputArr.each(function(){
					//将每个input的值放进结果集
					result.push($(this).text());
				});
				var  $inputArr2  =  $('.tags-text2');
				var  result2  =   [];
				$inputArr2.each(function() {
					//将每个input的值放进结果集
					result2.push($(this).text());
				});
				if($("#book-name").val().length==0){
					BookName=null;
				}if($("#book-type").val()==""){
					BookType = null;
				}if($("#copyright").val()=="-请选择-"){
					copyright=null;
				}if($("#book-press").val()==""){
					BookPrese=null;
				}if($("#addIMG").src=="../../resources/img/addimg.png"){
					$("#addIMG")[0].src=null;
				}if(result.length==0){
					result=null;
				}
				if(result2.length==0){
					result=null;
				}
					$.ajax({
						url:/*[[${#request.getContextPath()} + '/api/novel/' + ${novel.uniqueId.toString()} + '/edit']]*/"/nonexist",
						type: "post",
						dataType: "JSON",
						contentType:"application/json",
						data: JSON.stringify({
							"copyright": $("#copyright").val().length==0?null:$("#copyright").val()=='公版'?"NO_COPYRIGHT":$("#copyright").val()=='转载'?"REPRINT":$("#copyright").val()=='同人'?"FAN_FICTION":"ORIGINAL",
							"title": BookName,
							"authors": null,
							"description":BookIntro,
							"tags":null,
							"series": BookType,
							"publisher": BookPrese,
							"pubdate":getNowFormatDate() ,
							"coverImgUrl": $("#addIMG")[0].src
						}),
						success:function (data) {
							popup_over('icon-happy-l','#00ff0f',"修改书本信息成功");
								$(".modify-Novel").css("top",-1000+"px");
						},error(data){
							console.log( data);
						}
					})
			});
			//修改章节
			function ModifyChapter(chapterId) {
				var chapterIdArr = [];
				$(".getId").each(function(){
					chapterIdArr.push($(this).text());
				});
				var str5 = $("#modify-chapter-name").val();
				if($("#modify-chapter-name").val().length==0){
					str5=null;
				}
				const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
				$.ajax({
					url:contextPath+"/api/novel/chapter/"+chapterId+"/edit",
					type:"POST",
					dataType: "JSON",
					contentType:"application/json",
					data:JSON.stringify({
						title:str5,
						sections:chapterIdArr,
					}),success:function (data) {
						popup_over('icon-happy-l','#00ff0f',"修改章节成功");
					},error:function (data) {
						console.log(data);
					}
				})
			}
			//修改小节
			function ModifySection(SectionId){
				var activeEditor = tinymce.activeEditor;
				var editBody = activeEditor.getBody();
				activeEditor.selection.select(editBody);
				var text = activeEditor.selection.getContent({"format": "html"});
				var Text = activeEditor.selection.getContent({"format": "text"});
				var str3=$("#title-name").val();
				if($("#title-name").val().length==0){
					str3=null;
				}
				const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
				$.ajax({
					url:contextPath+"/api/novel/section/"+SectionId+"/edit",
					type:"POST",
					dataType: "JSON",
					contentType:"application/json",
					data: JSON.stringify({
						title:str3,
						text:text,
					}),success:function (data) {
						popup_over('icon-happy-l','#00ff0f',"修改内容成功");
					},error: function(jqXHR, textStatus, errorThrown) {
					const data = JSON.parse(jqXHR.responseText);
					alert("发送失败，请稍候再试:" + data.errorMessage);
					}
				})
			}
			function getContent(uniqueId){
				const contextPath=/*[[${#request.getContextPath()}]]*/'http://localhost:8080/future-novel';
				$.ajax({
					url:contextPath+"/api/novel/section/"+uniqueId,
					type:"GET",
					dataType: "JSON",
					contentType:"application/json",
					data: {}
					,success:function (data) {
						tinyMCE.activeEditor.setContent(data.text);
						$("#title-name").val(data.title);
					},error: function(data) {
						console.log(data);
					}
				})
			}
			$("#sure-bookName").click(function () {
					//创建章节的交互
					AddTitle();

			});
			$(".writer-list").on('click','.first',function(){
				$(this).next(".sec").slideToggle("slow");
			});
			//添加小节
			$(".writer-list").on('click','.modify',function(){
				$(".box").css("display","block");
				$("#title-name").css("height",40+"px");
				var str = $(this).attr("chapterid");
				let _this=this;
				$("#writer-release").click(function () {
					AddSection(str);
					$(_this).parent().append("<div class='sec' >\n" +
							"\t\t\t\t\t\t\t\t<div class='works-content'>\n" +
							"\t\t\t\t\t\t\t\t\t<span class=\"neirong\">" + "" + $("#SID").text() + "" + "</span>\n" +
							"\t\t\t\t\t\t\t\t\t<button class=\"modify2\">修改</button>\n" +
							"\t\t\t\t\t\t\t\t\t<button class=\"delete2\">删除</button>\n" +
							"\t\t\t\t\t\t\t\t</div>\n" +
							"\t\t\t\t\t\t\t</div>")
				});
			});
			$(".writer-list").on('click','.modify2',function () {
				$("#title-name").css("height",40+"px");
				$(".box").css("display","block");
				var str2 = $(this).attr("sectionid");
				let _this=this;
				getContent(str2)
				$("#writer-release").click(function () {
					ModifySection(str2);
					$(_this).prev().text($("#title-name").val());
					$(".box").css("display","none");
				});
			});
			$(".writer-list").on('click','.add',function () {
				$(".modify-chapter").css("marginTop",0);
				var str4 = $(this).attr("chapterid");
				let _this=this;
				$(".btn-sure").click(function () {
					ModifyChapter(str4);
					console.log(_this);
					if($("#modify-chapter-name").val().length!=0){
					$(_this).next().next().children("p").text($("#modify-chapter-name").val());
					}
				})
			});
			$("#closeInfo").click(function () {
				$(".modify-Novel").css("top",-1000+"px");
			})


			//富文本编辑器
			tinymce.init({
				selector:'textarea.content',
				height:"500", //高度
				width:"100%", //宽度
				toolbar_items_size: 'small', //控件大小
				menubar:true, //是否显示菜单栏
				plugins: ["link code"], //插件区，激活控件
				language:"zh_CN",//名称前后显示，影响控件显示位置
			});
            // 图片加载不出来时
			$("img").on("error", function(){
				$(this).attr("src", contextPath + "/img/loading.jpg");
			});
		</script>
	</body>
</html>
